package com.hongkzh.www.adv.service;

import com.google.common.collect.Lists;
import com.hongkzh.www.conmon.*;
import com.hongkzh.www.user.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.params.geo.GeoRadiusParam;

import java.util.*;

/**
 * @author martins
 */
public class MediaService extends BaseService {

    static AdvService advService = new AdvService();

    public List<Record> getCarouselList() {
        SqlPara sqlPara = Db.getSqlPara("media.getCarouselList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }


    public List<Record> categoryList() {
        SqlPara sqlPara = Db.getSqlPara("media.categoryList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public List<Record> getTop10List() {
        SqlPara sqlPara = Db.getSqlPara("media.getTop10List");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> getHotAdvList(int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("media.getHotAdvList");
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

//        List<Record> statics = advService.getStaticListByType("1");
        LinkedList<Record> llist = new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType", 1);
            doFilePath(r);
            llist.add(r);
//            for (Record static1 : statics
//            ) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    llist.add(static1);
//                    break;
//                }
//            }
        }
        Page<Record> records2 = new Page<Record>(llist, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());


        return records2;

    }

    private void initMediaData() {

        if (!RedisTool.exists(StaticPublic.GEOMEDIAEXITSKEY)) {
            RedisTool.del(StaticPublic.GEOMEDIAKEY);
            SqlPara sqlPara = Db.getSqlPara("media.getMediaAdvList");
            List<Record> records = Db.find(sqlPara);
            if (null != records && records.size() > 0) {
                RedisTool.setex(StaticPublic.GEOMEDIAEXITSKEY, StaticPublic.GEOMEDIAEXITSKEYTIME, "1");
                for (Record r : records) {
                    RedisTool.geoadd(StaticPublic.GEOMEDIAKEY, r.getDouble("longitude"), r.getDouble("latitude"), r.getStr("id"));
                }
            }

        }
    }

    public Page<Record> getNearbyAdvList(double latitude, double longitude, int pageNumber) {

        initMediaData();

        List<Record> records = Lists.newArrayList();
        Page<Record> p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, 0, 0);
        List<GeoRadiusResponse> list = RedisTool.georadius(StaticPublic.GEOMEDIAKEY, longitude, latitude, StaticPublic.BAI, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().sortAscending().count(6 * pageNumber));
        int totalRow = list.size();

        int totalPage = (int) (totalRow / StaticPublic.PAGESIZE);
        if (null != list && list.size() > 0) {
            list.subList(0, StaticPublic.PAGESIZE * (pageNumber - 1)).clear();
        }
        SqlPara sqlPara;
//        List<Record> statics = advService.getStaticListByType("1");

        for (GeoRadiusResponse g : list) {
            String id = new String(g.getMember());
            sqlPara = Db.getSqlPara("media.getMediaAdvById", id);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                r.set("advType", 1);
                r.set("distance", g.getDistance());
                doFilePath(r);

                records.add(r);
//                for (Record static1 : statics
//                ) {
//                    if (0 == MathRandom.PercentageRandom()) {
//                        static1.set("advType", 2);
//                        records.add(static1);
//                        break;
//                    }
//                }
            }
        }
        if (null != records && records.size() > 0) {
            p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, totalPage, totalRow);
        }
        return p;
    }

    public List<Record> getHotNewsList() {
        SqlPara sqlPara = Db.getSqlPara("media.getHotNewsList");
        return Db.find(sqlPara);
    }

    public List<Record> getCirclesList() {
        SqlPara sqlPara = Db.getSqlPara("media.getCirclesList");
        return Db.find(sqlPara);
    }


    public List<Record> AllCategoryList() {
        SqlPara sqlPara = Db.getSqlPara("media.ALLCategoryList");
        List<Record> records = Db.find(sqlPara);
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public List<Record> getCategoryCarouselList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCarouselList", categoryId);
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }


    public List<Record> getCategoryTop10List(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryTop10List", categoryId);
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }


    public Page<Record> getMediaHotAdvList(int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("media.getMediaHotAdvListEx");

        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);


        SqlPara sqlPara1 = Db.getSqlPara("media.getMediaRedPackets");
        Page<Record> recordPage = Db.paginate(pageNumber , 4, sqlPara1);
//        List<Record> statics = advService.getStaticListByType("1");
        LinkedList<Record> llist = new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType", 1);
            r.set("type", 1);
            doFilePath(r);
            llist.add(r);
//            for (Record static1 : statics
//            ) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    llist.add(static1);
//                    break;
//                }
//            }
        }
        for (Record r : recordPage.getList()) {
            r.set("advType", 1);
            r.set("type", 1);
            doFilePath(r);
            llist.add(r);
        }
        Collections.shuffle(llist);
        Page<Record> records2 = new Page<Record>(llist, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());


        return records2;
    }

    public Page<Record> getMainHotAdvList(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("media.getMainHotAdvList");
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
//        List<Record> statics = advService.getStaticListByType("1");
        LinkedList<Record> llist = new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType", 1);
//            r.set("type", r.get("type"));
//            r.set("type", 1);
            doFilePath(r);
            llist.add(r);
//            for (Record static1 : statics) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    llist.add(static1);
//                    break;
//                }
//            }
        }
        Record randomRedPack = Db.findFirst(Db.getSqlPara("media.getMainRedPackHotAdvList", loginUid));
        if (null != randomRedPack) {
            randomRedPack.set("advType", 1);
//            randomRedPack.set("type", 1);
            doImgPath(randomRedPack);
            llist.add(randomRedPack);
        }
        Collections.shuffle(llist);
        Page<Record> records2 = new Page<Record>(llist, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());


        return records2;
    }

    public Page<Record> getCategorySearchAdvList(int pageNumber, String categoryId) {
        Kv cond = Kv.by("categoryId", categoryId);
        SqlPara sqlPara = Db.getSqlPara("media.getCategorySearchAdvList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
//        List<Record> statics = advService.getStaticListByType("1");
        LinkedList<Record> llist = new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType", 1);
            doFilePath(r);
            llist.add(r);
//            for (Record static1 : statics
//            ) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    llist.add(static1);
//                    break;
//                }
//            }
        }
        Page<Record> records2 = new Page<Record>(llist, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
        return records2;
    }

    public Page<Record> getCategoryHotAdvList(int pageNumber, String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryHotAdvList", categoryId);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
//        List<Record> statics = advService.getStaticListByType("1");
        LinkedList<Record> llist = new LinkedList<>();
        for (Record r : records.getList()) {
            r.set("advType", 1);
            doFilePath(r);
            llist.add(r);
//            for (Record static1 : statics
//            ) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    llist.add(static1);
//                    break;
//                }
//            }
        }
        Page<Record> records2 = new Page<Record>(llist, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
        return records2;
    }

    private void initMediaDataByCategory(String categoryId) {
        String key = String.format(StaticPublic.GEOMEDIAEXITSKEYCATEGORY, categoryId);
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        if (!RedisTool.exists(key)) {
            RedisTool.del(categoryKey);
            SqlPara sqlPara = Db.getSqlPara("media.getMediaAdvCategoryList", categoryId);
            List<Record> records = Db.find(sqlPara);
            if (null != records && records.size() > 0) {
                RedisTool.setex(key, StaticPublic.GEOMEDIAEXITSKEYTIME, "1");
                for (Record r : records) {
                    RedisTool.geoadd(categoryKey, r.getDouble("longitude"), r.getDouble("latitude"), r.getStr("id"));
                }
            }

        }
    }

    private void initMediaALLDataByCategory(String categoryId) {
        String key = String.format(StaticPublic.GEOMEDIAEXITSKEYCATEGORY, categoryId);
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        if (!RedisTool.exists(key)) {
            RedisTool.del(categoryKey);
            SqlPara sqlPara = Db.getSqlPara("media.getMediaAdvList");
            List<Record> records = Db.find(sqlPara);
            if (null != records && records.size() > 0) {
                RedisTool.setex(key, StaticPublic.GEOMEDIAEXITSKEYTIME, "1");
                for (Record r : records) {
                    RedisTool.geoadd(categoryKey, r.getDouble("longitude"), r.getDouble("latitude"), r.getStr("id"));
                }
            }

        }
    }

    public Page<Record> getCategoryNearbyAdvList(double latitude, double longitude, int pageNumber, String categoryId) {
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        initMediaDataByCategory(categoryId);
        SqlPara sqlPara;
        List<Record> records = Lists.newArrayList();
        Page<Record> p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, 0, 0);
        List<GeoRadiusResponse> list = RedisTool.georadius(categoryKey, longitude, latitude, StaticPublic.BAI, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().sortAscending().count(100));
        int totalRow = list.size();
        int totalPage = (int) (totalRow / StaticPublic.PAGESIZE);
        if (totalRow % (long) StaticPublic.PAGESIZE != 0L) {
            ++totalPage;
        }

        if (null != list && list.size() > 0 && list.size() >= StaticPublic.PAGESIZE * (pageNumber - 1)) {
            list.subList(0, StaticPublic.PAGESIZE * (pageNumber - 1)).clear();
        } else {
            list = Collections.emptyList();
        }

        for (GeoRadiusResponse g : list) {
            String id = new String(g.getMember());
            sqlPara = Db.getSqlPara("media.getMediaAdvById", id);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                r.set("advType", 1);
                r.set("distance", g.getDistance());
                doFilePath(r);
                records.add(r);
            }
        }
        if (null != records && records.size() > 0) {
            p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, totalPage, totalRow);
        }
        return p;

    }

    public Page<Record> getMediaNearbyAdvList(double latitude, double longitude, int pageNumber) {
        String categoryId = latitude + "-" + longitude;
        String categoryKey = String.format(StaticPublic.GEOMEDIAKEYCATEGORY, categoryId);
        initMediaALLDataByCategory(categoryId);
        SqlPara sqlPara;
        List<Record> records = Lists.newArrayList();
        Page<Record> p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, 0, 0);
        List<GeoRadiusResponse> list = RedisTool.georadius(categoryKey, longitude, latitude, StaticPublic.BAI, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().sortAscending().count(50));

        int totalRow=0;
        int totalPage=0;
       /* sqlPara = Db.getSqlPara("media.getCount");
        Record count= Db.findFirst(sqlPara);*/

        List<GeoRadiusResponse> list2;
        if (null != list && list.size() > 0 && list.size() >= StaticPublic.PAGESIZE * (pageNumber - 1)) {
            totalRow = list.size(); // count.getLong("count").intValue();
            //totalRow=totalRow>list.size()?list.size():totalRow;
            totalPage = (int) (totalRow / StaticPublic.PAGESIZE);
            if (totalRow % (long) StaticPublic.PAGESIZE != 0L) {
                ++totalPage;
            }
            list2 = list.subList(StaticPublic.PAGESIZE * (pageNumber - 1), (StaticPublic.PAGESIZE * pageNumber > totalRow ? totalRow : StaticPublic.PAGESIZE * pageNumber));
        } else {
            list2 = Collections.emptyList();
        }


//        List<Record> statics = advService.getStaticListByType("1");


        for (GeoRadiusResponse g : list2) {
            String id = new String(g.getMember());
            sqlPara = Db.getSqlPara("media.getMediaAdvById", id);
            Record r = Db.findFirst(sqlPara);
            if (null != r) {
                r.set("advType", 1);
                r.set("distance", g.getDistance());
                doFilePath(r);

                records.add(r);
//                for (Record static1 : statics
//                ) {
//                    if (0 == MathRandom.PercentageRandom()) {
//                        static1.set("advType", 2);
//                        records.add(static1);
//                        break;
//                    }
//                }
            }
        }
        if (null != records && records.size() > 0) {
            p = new Page<Record>(records, pageNumber, StaticPublic.PAGESIZE, totalPage, totalRow);
        }
        return p;

    }

    public Record getCategoryQuery(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryQuery", categoryId);
        Record record = Db.findFirst(sqlPara);
        record.set("categorys", null);
        if ("1".equals(record.get("isCategoryQuery"))) {
            sqlPara = Db.getSqlPara("media.getCategoryListById", categoryId);
            List<Record> list = Db.find(sqlPara);
            if (null != list && list.size() > 0) {
                record.set("categorys", list);
            }
        }

        return record;
    }

    public List<Record> getCategoryCirclesList(String categoryId) {
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCirclesList", categoryId);
        return Db.find(sqlPara);
    }

    public Page<Record> getCategoryCirclesList(String categoryId, int pageNumber, String sortId, String sortValue) {
        if ("create_date".equals(sortId)) {
            sortId = " a.create_date ";
        } else if ("user_count".equals(sortId)) {
            sortId = " b.user_count ";
        }
        Kv cond = Kv.by("categoryId", categoryId).set("order", " order by " + sortId + " " + sortValue);
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCirclesList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;
    }

    public Page<Record> getMediaSearchCirclesList(int pageNumber, String categoryId) {
        Kv cond = Kv.by("categoryId", categoryId);
        SqlPara sqlPara = Db.getSqlPara("media.getMediaSearchCirclesList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        for (Record r : records.getList()) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> getMediaCirclesList(int pageNumber, String sortId, String sortValue) {
        if ("create_date".equals(sortId)) {
            sortId = " a.create_date ";
        } else if ("user_count".equals(sortId)) {
            sortId = " b.user_count ";
        }
        Kv cond = Kv.by("order", " order by " + sortId + " " + sortValue);
        SqlPara sqlPara = Db.getSqlPara("media.getCategoryCirclesList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;
    }

    public List<Record> getRecommendTop10List() {
        SqlPara sqlPara = Db.getSqlPara("media.getRecommendTop10List");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public List<Record> getMediaTop10List() {
        SqlPara sqlPara = Db.getSqlPara("media.getMediaTop10List");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public Page<Record> getInfoMediaAdvCommentList(int pageNumber, String id, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("media.getInfoMediaAdvCommentList", id);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        return records;

    }

    public Record getAdvById(String id, String userId, String sourceType) {
        {
            SqlPara sqlPara = Db.getSqlPara("media.getAdvById", id, userId);
            Record r = Db.findFirst(sqlPara);
            if (r == null) {
                throw new BusinessException("网络异常！");
            }
            r.set("mediaType", "0");
            if (r != null) {
                sqlPara = Db.getSqlPara("media.getPhotographys", id);
                List<Record> photographys = Db.find(sqlPara);
                for (Record a : photographys
                ) {
                    doImgPath(a);
                }
                r.set("photographys", photographys);

                r.set("isRed", "0");
                if (r.getInt("totalMoney") > 0) {
                    r.set("isRed", "1");
                }
                r.remove("totalMoney");
                r.set("collectionState", "0");
                if (StrKit.notBlank(r.getStr("collectionId"))) {
                    r.set("collectionState", "1");
                }
                r.set("praiseState", "0");
                if (StrKit.notBlank(r.getStr("praiseId"))) {
                    r.set("praiseState", "1");
                }

                sqlPara = Db.getSqlPara("user.getUserAlbumsById", r.getStr("uid"));
                List<Record> albums = Db.find(sqlPara);
                for (Record a : albums
                ) {
                    doImgPath(a);
                }
                r.set("albums", albums);

                if (StrKit.notBlank(r.getStr("seeking"))) {
                    r.set("mediaType", "1");
                    List<Record> infos = Lists.newArrayList();
                    sqlPara = Db.getSqlPara("user.getUserInfoById", r.getStr("uid"), userId);
                    Record record = Db.findFirst(sqlPara);
                    infos.add(new Record().set("id", "家乡").set("name", RedisTool.hgetArea(record.get("located"))));
                    infos.add(new Record().set("id", "星座").set("name", RedisTool.hgetDict("hk_user_constellation:" + record.getStr("constellation"))));
                    infos.add(new Record().set("id", "职业").set("name", record.getStr("occupation")));
                    //infos.add(new Record().set("id","注册日期").set("name",DateUtil.FormatDate2(record.get("createDate"))));

                    r.set("infos", infos);

                }


                r.set("imgSrc1", r.getStr("imgSrc"));
                doFilePath(r);
                r.set("imgSrc", r.getStr("imgSrc1"));
            }
            sqlPara = Db.getSqlPara("media.getMediaTagList", id);
            List<Record> tags = Db.find(sqlPara);
            r.set("tags", null);
            if (null != tags && tags.size() > 0) {
                r.set("tags", tags);
            }

            sqlPara = Db.getSqlPara("media.getMediaUserProductList", id);
            List<Record> products = Db.find(sqlPara);
            r.set("products", null);
            if (null != products && products.size() > 0) {
                for (Record p : products
                ) {
                    doImgPath(p);
                }
                r.set("products", products);
            }
            r.set("nextMediaAdvId", "");
            // 1其他 2用户个人中心
            if ("1".equals(sourceType)) {

                sqlPara = Db.getSqlPara("media.nextMediaAdvId", id);
                Record r2 = Db.findFirst(sqlPara);
                if (null != r2) {
                    r.set("nextMediaAdvId", r2.get("id"));
                }

            } else {
                sqlPara = Db.getSqlPara("media.nextUserMediaAdvId", id, userId);
                Record r2 = Db.findFirst(sqlPara);
                if (null != r2) {
                    r.set("nextMediaAdvId", r2.get("id"));
                }
            }


            return r;

        }
    }

    public List<Record> getUserCategoryList(String loginUid, String isFirst) {
        SqlPara sqlPara = Db.getSqlPara("media.getUserCategoryList", loginUid);
        List<Record> list = Db.find(sqlPara);
        if (StrKit.notBlank(isFirst) && "1".equals(isFirst)) {
            return list;
        }
        if (null == list || list.size() == 0) {
            sqlPara = Db.getSqlPara("media.getSystemCategoryList");
            list = Db.find(sqlPara);
        }

        return list;
    }

    public Record getUserInfo(String loginUid, String id) {

        SqlPara sqlPara = Db.getSqlPara("user.getUserInfoById", id, loginUid);
        Record record = Db.findFirst(sqlPara);
        if (null == record) {
            return record;
        }
        record.set("loginTime", DateUtil.CalculateTime(record.getStr("loginTime")));
        doFilePath(record);
        List<Record> infos = Lists.newArrayList();
        infos.add(new Record().set("id", "家乡").set("name", RedisTool.hgetArea(record.get("located"))));
        infos.add(new Record().set("id", "星座").set("name", RedisTool.hgetDict("hk_user_constellation:" + record.getStr("constellation"))));
        infos.add(new Record().set("id", "职业").set("name", record.getStr("occupation")));
        infos.add(new Record().set("id", "注册日期").set("name", DateUtil.FormatDate2(record.get("createDate"))));
        String f = record.getStr("friendId");
        infos.add(new Record().set("id", "关系").set("name", StrKit.isBlank(f) ? "陌生人" : "好友"));
        record.set("infos", infos);


        List<Record> labels = Lists.newArrayList();
        sqlPara = Db.getSqlPara("media.getUserCategoryList", id);
        List<Record> ls = Db.find(sqlPara);
        for (Record r : ls
        ) {
            labels.add(new Record().set("id", r.getStr("categoryId")).set("name", r.getStr("name")));
        }
        record.set("labels", labels);
        sqlPara = Db.getSqlPara("user.getUserFollowsById", id);
        List<Record> follows = Db.find(sqlPara);
        for (Record r : follows
        ) {
            doFilePath(r);
        }
        record.set("follows", follows);
        sqlPara = Db.getSqlPara("user.getUserFollowCountsById", id);
        record.set("followCounts", Db.findFirst(sqlPara).get("count"));


        sqlPara = Db.getSqlPara("user.getUserCirclesById", id);
        List<Record> circles = Db.find(sqlPara);
        for (Record r : circles
        ) {
            doFilePath(r);
        }
        record.set("circles", circles);
        sqlPara = Db.getSqlPara("user.getUserCircleCountsById", id);
        record.set("circleCounts", Db.findFirst(sqlPara).get("count"));


        sqlPara = Db.getSqlPara("user.getUserAlbumsById", id);
        List<Record> albums = Db.find(sqlPara);
        for (Record r : albums
        ) {
            doFilePath(r);
        }
        record.set("albums", albums);


        sqlPara = Db.getSqlPara("user.friendDynamicList", id);
        List<Record> dynamics = Db.find(sqlPara);
        for (Record r : dynamics
        ) {
            doFilePath(r);
        }
        record.set("dynamics", dynamics);
        sqlPara = Db.getSqlPara("user.friendDynamicCountList", id);
        record.set("dynamicCounts", Db.findFirst(sqlPara).get("count"));


        return record;
    }

    public Page<Record> getUserMediasList(String uid, int pageNumber, String sortId) {
        if ("create_date".equals(sortId)) {
            sortId = " a.create_date ";
        } else if ("user_count".equals(sortId)) {
            sortId = " b.user_count ";
        }
        Kv cond = Kv.by("userId", uid).set("order", " order by " + sortId + " desc ");
        SqlPara sqlPara = Db.getSqlPara("media.getUserMediasList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
            //r.set("playCount",BigNumberFormat.dataFormat(r.get("playCount")));
            r.set("createDate", DateUtil.FormatDate(r.get("createDate")));
        }
        return records;
    }

    public Page<Record> getUserProductsList(String uid, int pageNumber, String sortId) {
        if ("create_date".equals(sortId)) {
            sortId = " a.create_date ";
        } else if ("user_count".equals(sortId)) {
            sortId = " b.user_count ";
        }
        Kv cond = Kv.by("userId", uid).set("order", " order by " + sortId + " desc ");
        SqlPara sqlPara = Db.getSqlPara("media.getUserProductsList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
            r.set("createDate", DateUtil.FormatDate(r.get("createDate")));
        }
        return records;
    }

    @Before(Tx.class)
    public void addUserCategory(String loginUid, String[] category) {
        String id;
        Record record;
        SqlPara sqlPara;
        sqlPara = Db.getSqlPara("friend.deleteCategoryByUserId", loginUid);
        Db.update(sqlPara);
        int i = 1;
        for (String c : category) {

            sqlPara = Db.getSqlPara("friend.getCategoryById", c);
            record = Db.findFirst(sqlPara);
            if (record != null) {
                id = IdGen.uuid();
                sqlPara = Db.getSqlPara("friend.userCategory", id, loginUid, c, record.get("imgSrc"), record.get("type"), i);
                Db.update(sqlPara);
                i++;
            }

        }

    }

    public Record getRecruitById(String loginUid, String recruitId) {
        SqlPara sqlPara = Db.getSqlPara("media.getRecruitById", recruitId);
        Record r = Db.findFirst(sqlPara);
        doCache(r);
        r.set("category", r.getStr("industryName"));
        r.set("scale", r.getStr("scaleName"));
        r.set("listing", r.getStr("stageName"));
        doFilePath(r);

        return r;
    }

    public Page<Record> getCategoryQueryList(String categoryId, int pageNumber, String provinceId) {
        Kv cond = new Kv();
        if (StrKit.notBlank(categoryId)) {
            // sb.append(" and c.category_id='").append(categoryId).append("'");
            cond.set("categoryId", categoryId);
            // cond.set(" c.category_id=",categoryId);
        }
        if (StrKit.notBlank(provinceId)) {
            //sb.append("  and  a.province_id='").append(provinceId).append("'");
            cond.set("provinceId", provinceId);
        }

        SqlPara sqlPara = Db.getSqlPara("media.getCategoryQueryList", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
//        List<Record> statics = advService.getStaticListByType("1");
        List<Record> res = new ArrayList<>();
        for (Record r : records.getList()
        ) {
            r.set("advType", 1);
            doImgPath(r);
            doNumberPath(r);
            res.add(r);
//            for (Record static1 : statics
//            ) {
//                if (0 == MathRandom.PercentageRandom()) {
//                    static1.set("advType", 2);
//                    res.add(static1);
//                    break;
//                }
//            }

        }

        return new Page<Record>(res, records.getPageNumber(), records.getPageNumber(), records.getTotalPage(), records.getTotalRow());

    }

    public Record getCategoryById(String id) {

        return Db.findFirst(Db.getSqlPara("media.getCategoryById", id));
    }

    @Before(Tx.class)
    public String reward(String uid, String id, int money) throws Exception {
        Record r = Db.findFirst(Db.getSqlPara("media.getAdvById", id, uid));
        if (r == null) {
            throw new BusinessException("已下架");
        }
        UserService us = Enhancer.enhance(UserService.class);
        us.reduceIntegral(uid, money, "打赏消费");
        us.addIntegral(r.getStr("uid"), money, "收入");
        int i = Db.update(Db.getSqlPara("adv.updateDataReward", id, money));
        if (i == 0) {
            Db.update(Db.getSqlPara("adv.insertDataReward", IdGen.uuid(), id, money));
        }

        return Db.findFirst(Db.getSqlPara("adv.getDataReward", id)).getStr("rewardCount");
    }

    @Before(Tx.class)
    public void buyBooth(String loginUid) throws Exception {
        UserService userService = Enhancer.enhance(UserService.class);

        int boothMoney = Db.findFirst(Db.getSqlPara("friend.getBoothMoney")).getInt("money");
        userService.reduceIntegral(loginUid, boothMoney, "购买自媒体展位");

    }

    public Page<Record> myVideo(String categoryId, int pageNumber, String loginUid, String sourceId) {
        StringBuffer sb = new StringBuffer();
        if (StrKit.notBlank(categoryId)) {
            sb.append(" and c.category_id='").append(categoryId).append("'");
        }
        if (StrKit.notBlank(loginUid)) {
            sb.append("  and  a.user_id='").append(loginUid).append("'");
        }
        if (StrKit.notBlank(sourceId)) {
            sb.append("  and  a.source_id='").append(sourceId).append("'");
        }
        Kv cond = Kv.by("del", '0').set("order", sb.toString());
        SqlPara sqlPara = Db.getSqlPara("media.myVideo", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        List<Record> list = Db.find(Db.getSqlPara("media.getMediaProImg", sourceId));
        for (Record r : records.getList()) {
            doImgPath(r);
            doNumberPath(r);
        }

        if (StrKit.notBlank(sourceId)) {
            for (Record record : list) {
                String imgSrc = record.getStr("mediaImgSrc");
                if (StrKit.notBlank(imgSrc) && imgSrc.indexOf("http") < 0) {
                    record.set("mediaImgSrc", PropKit.get("fileServer") + imgSrc);
                }
            }
            if (list.size() > 0) {
                records.getList().get(0).set("mediaImgSrc", list);
            }
        }
        return records;
    }


   /* public Page<Record> myVideoById(String categoryId, int pageNumber, String loginUid, String sourceId) {
        StringBuffer sb = new StringBuffer();
        if (StrKit.notBlank(categoryId)) {
            sb.append(" and c.category_id='").append(categoryId).append("'");
        }
        if (StrKit.notBlank(loginUid)) {
            sb.append("  and  a.user_id='").append(loginUid).append("'");
        }
        if (StrKit.notBlank(sourceId)) {
            sb.append("  and  a.source_id='").append(sourceId).append("'");
        }
        Kv cond = Kv.by("del", '0').set("order", sb.toString());
        SqlPara sqlPara = Db.getSqlPara("media.myVideoById", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        for (Record r : records.getList()
        ) {
            doImgPath(r);
            doNumberPath(r);
        }
        return records;
    }*/

    public List myVideoCategory(String loginUid) {
        return Db.find(Db.getSqlPara("media.myVideoCategory", loginUid));
    }

    public Page<Record> myTravels(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("media.myTravels", loginUid);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        for (Record r : records.getList()
        ) {
            doImgPath(r);
            doNumberPath(r);
        }
        return records;
    }

    public Page<Record> myPosts(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("friend.myPosts", loginUid);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);
        for (Record r : records.getList()
        ) {
            doImgList(r);
            doImgPath(r);
            doNumberPath(r);
        }
        return records;
    }

    private void doImgList(Record r) {
        List<String> imgs = Lists.newArrayList();
        r.set("imgList", imgs);
        if ("1".equals(r.getStr("type")) && StrKit.notBlank(r.getStr("content"))) {
            Document containerDoc = Jsoup.parse(r.getStr("content"));
            Elements e = containerDoc.select("img");
            int i = 0;
            for (Element ee : e) {
                if (i > 3) {
                    break;
                }
                imgs.add(ee.attr("src"));
                i++;
            }
            r.set("imgList", imgs);
        }
    }

    public Page<Record> myRepliesPosts(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("friend.myRepliesPosts", loginUid);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        List<Record> list = records.getList();
        List<String> rlist = Lists.newArrayList();
        List<Record> rlist2 = Lists.newArrayList();
        List<Record> rlist3 = Lists.newArrayList();
        for (Record r : list
        ) {
            if (!rlist.contains(r.getStr("postId"))) {
                rlist.add(r.getStr("postId"));
            }
        }
        Record r;
        List r3;
        String userName = "";
        for (String s : rlist) {
            sqlPara = Db.getSqlPara("friend.myPostsTitleById", s);
            r = Db.findFirst(sqlPara);
            r.set("postId", s);
            for (Record r1 : list) {
                rlist3.add(r1);
            }
            sqlPara = Db.getSqlPara("friend.myReplyPosts", s);
            r3 = Db.find(sqlPara);
            rlist3.addAll(r3);
            for (Record r4 : rlist3
            ) {
                userName = "";
                if (StrKit.notBlank(r4.getStr("ruserId"))) {
                    sqlPara = Db.getSqlPara("user.getUserHeadImgInfo", r4.getStr("ruserId"));
                    userName = Db.findFirst(sqlPara).getStr("name");
                }
                r4.set("userName", userName);
            }
            Collections.sort(rlist3, new Comparator<Record>() {

                @Override
                public int compare(Record o1, Record o2) {


                    return o1.getDate("createDate").before(o2.getDate("createDate")) ? 1 : 0;
                }
            });

            r.set("comments", rlist3);
            rlist2.add(r);
        }


        return new Page<Record>(rlist2, records.getPageNumber(), records.getPageSize(), records.getTotalPage(), records.getTotalRow());
    }

    public Page<Record> myDelPosts(int pageNumber, String loginUid, String delType) {
        SqlPara sqlPara = Db.getSqlPara("friend.myDelPosts", loginUid, delType);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);

        return records;
    }

    public Page<Record> myPraisePost(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("friend.myPraisePost", loginUid);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);
        for (Record r : records.getList()) {
            doImgPath(r);
        }
        return records;
    }

    public Page<Record> myForwardPost(int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("friend.myForwardPost", loginUid);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);
        for (Record r : records.getList()) {
            doImgPath(r);
        }
        return records;
    }

    public Page<Record> myCollection(String categoryId, int pageNumber, String loginUid) {
        StringBuffer sb = new StringBuffer();
        if (StrKit.notBlank(categoryId)) {
            sb.append(" and c.category_id='").append(categoryId).append("'");
        }
        if (StrKit.notBlank(loginUid)) {
            sb.append("  and  vc.user_id='").append(loginUid).append("'");
        }
        Kv cond = Kv.by("del", '0').set("order", sb.toString());
        SqlPara sqlPara = Db.getSqlPara("media.myCollection", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);
        for (Record r : records.getList()
        ) {
            doImgPath(r);
            doNumberPath(r);
        }
        return records;

    }

    public List myCollectionCategory(String loginUid) {
        return Db.find(Db.getSqlPara("media.myCollectionCategory", loginUid));
    }

    public Page<Record> myPraise(String categoryId, int pageNumber, String loginUid) {

        StringBuffer sb = new StringBuffer();
        if (StrKit.notBlank(categoryId)) {
            sb.append(" and c.category_id='").append(categoryId).append("'");
        }
        if (StrKit.notBlank(loginUid)) {
            sb.append("  and  vc.user_id='").append(loginUid).append("'");
        }
        Kv cond = Kv.by("del", '0').set("order", sb.toString());
        SqlPara sqlPara = Db.getSqlPara("media.myPraise", cond);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.LARGEPAGESIZE, sqlPara);
        for (Record r : records.getList()
        ) {
            doImgPath(r);
            doNumberPath(r);
        }
        return records;
    }

    public List myPraiseCategory(String loginUid) {
        return Db.find(Db.getSqlPara("media.myPraiseCategory", loginUid));
    }


    public Record searchHistory(String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("media.hotsearch");
        List<Record> hots = Db.find(sqlPara);
        Record r = new Record();
        r.set("hosts", hots);
        r.set("historys", null);
        if (StrKit.notBlank(loginUid)) {
            sqlPara = Db.getSqlPara("media.searchHistory", loginUid);
            List<Record> historys = Db.find(sqlPara);
            r.set("historys", historys);
        }

        return r;
    }


    @Before(Tx.class)
    public void deleteSearchHistory(String loginUid, String historyId) {
        Db.update(Db.getSqlPara("media.deleteSearchHistory", historyId, loginUid));
    }

    @Before(Tx.class)
    public void emptySearchHistory(String loginUid) {
        Db.update(Db.getSqlPara("media.emptySearchHistory", loginUid));
    }

    public List<Record> searchMedia(String loginUid, String name) {
        return Db.find(Db.getSqlPara("media.searchMedia", name));
    }

    public Page<Record> searchMediaList(String title, int pageNumber) {


        SqlPara sqlPara = Db.getSqlPara("media.searchMediaList", title);
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;
    }

    @Before(Tx.class)
    public void saveSearch(String loginUid, String title) {
        Record record = Db.findFirst(Db.getSqlPara("media.searchHistoryByName", loginUid, title));
        if (record == null) {
            Db.update(Db.getSqlPara("media.saveSearch", IdGen.uuid(), loginUid, title));

        } else {
            Db.update(Db.getSqlPara("media.updateSearch", loginUid, title));
        }
        record = Db.findFirst(Db.getSqlPara("media.searchHotHistoryByName", title));
        if (record == null) {
            Db.update(Db.getSqlPara("media.savehotSearch", IdGen.uuid(), loginUid, title));
        } else {
            Db.update(Db.getSqlPara("media.updatehotSearch", title));
        }


    }

    public Record updateVersion(int version,String isIos) {
        //ios
        Record record = new Record();
        if (StrKit.notBlank(isIos) && isIos.equals("1")){
            record = Db.findFirst(Db.getSqlPara("media.selectUpdateVersionAndorid",isIos));
        }else{
            //android
            record = Db.findFirst(Db.getSqlPara("media.selectUpdateVersionIos",isIos));
        }

        if (record == null) {
            return null;
        }
        int version2 = Integer.parseInt(record.getStr("version").replaceAll("\\.", ""));
        if (version2 > version) {
            String url = record.getStr("url");
            if (StrKit.notBlank(url) && url.indexOf("http") < 0) {
                record.set("url", PropKit.get("fileServer") + url);
            }
            return record;
        }

        return null;
    }

    public Record iosConfig() {
        return Db.findFirst(Db.getSqlPara("media.iosConfig"));
    }

    public Record iosConfigByiosVersion(String version) {
        return Db.findFirst(Db.getSqlPara("media.iosConfigByVersion",version));
    }

}
